import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import storage from '../../shared/storage';
import {HomeService} from "../home.service";
import mqttTool from '../../shared/mqtt/mqttTool';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import { TranslateService } from '@ngx-translate/core';
import { Router, ActivatedRoute, NavigationEnd , ParamMap } from '@angular/router';
import SysData from '../../shared/sysData';
import Mysocket from '../../shared/mySocket';
@Component({
  selector: 'app-device-debug-rf',
  templateUrl: './device-debug-rf.component.html',
  styleUrls: ['./device-debug-rf.component.scss']
})
export class DeviceDebugRfComponent implements OnInit {
    @Output() close: EventEmitter<boolean> = new EventEmitter<boolean>();
    @Output() offLine: EventEmitter<boolean> = new EventEmitter<boolean>();
  state=false;  //默认停止
  isSpinning:boolean=false;
  signalWave="";
  rfWaveOption1=[];//停止  运行
  rfWaveOption2=[];  //w1  w2  both
  isW1LightShow:boolean=false;//w1是否亮灯
  isW2LightShow:boolean=false;//w2是否亮灯
  isBothLightShow:boolean=false;//both是否亮灯
  isAMsubsidiaryShow:boolean=false;//副天线是否亮灯
  currentKeyVal={}; //现在的天线，key，value集合
  alarmTestItem={};//报警测试
  readParamItem={};//读取参数
  restoreFactoryItem={};//恢复出厂设置
  waveDataXList=[];//X轴
  waveDataY1List=[];//Y1
  waveDataY2List=[];//Y2
  signalWaveOption={};
  formatOne = percent =>"";
  //moduleCode
  rfAlarmList:any=storage.getSessionStorage("AA10_EAS_RF_ALARM_CMD");  //RF报警设置
  rfCmdList:any=storage.getSessionStorage("AA10_EAS_RF_CMD");   //RF通用命令（测试，出厂，波形图）
  rfFunctionList:any=storage.getSessionStorage("AA10_EAS_RF_FUNCTION_CMD"); //RF天线性能配置
  rfWaveCmdList:any=storage.getSessionStorage("AA10_EAS_RF_WAVE_CMD"); //EAS_RF_WAVE_CMD RF波形调试(带宽，阈值)
  //选择项
  rfWaveOptionList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_RF_WAVE");//RF波形图参数，停止  W1 W2 BOTH
  bandWidthOption:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_BANDWIDTH");//带宽
  alermColorList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_ALARMCOLOR"); // 报警颜色
  lightColorList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_RF_LIGHTCOLOR");//常亮颜色
  soundLengthLish:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_SOUNDLENGTH");//音长
  toneList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_TONE");//音调
  alermEnableList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_ALARMENABLE"); //报警使能
  hitCountList:any=storage.getSessionStorage("AA10_EAS_DEBUG_PARAM_HITCOUNT");//命中次数
  LoginForm:any=storage.getSessionStorage('LoginForm');
  displayHitCount:number;
  constructor(
    private router: Router,
    private homeService:HomeService,
    private message:NzMessageService,
    private modalService: NzModalService,
    private translateService:TranslateService) { }
  ngOnInit() {
    this.rfWaveOption2=this.rfWaveOptionList.splice(1,3); 
    this.rfWaveOption1=this.rfWaveOptionList.splice(0,1);
    for(let i=0;i<120;i++){
      this.waveDataXList.push(i);
    }
    this.rfCmdList.forEach(item=>{
      if(item.key=='f2'){
        //信号波形
        this.currentKeyVal['key'+item.key]=this.rfWaveOption1[0].value; 
      } else if(item.key=='63'){
        //报警测试
        this.alarmTestItem=JSON.parse(JSON.stringify(item));
      } else if(item.key=='58'){
        //读取参数
        this.readParamItem=JSON.parse(JSON.stringify(item));
      }else if(item.key=='fa'){
        //恢复出厂设置
        this.restoreFactoryItem=JSON.parse(JSON.stringify(item));
      }
    });
    //RF波形调试
    this.rfWaveCmdList.forEach(item=>{
      if(item.key=='0f' || item.key=='10'){
        item['min']=0;
        item['max']=30;
        this.currentKeyVal['key'+item.key]=0;  
      } else if(item.key=='13' || item.key=='14'){
        item['min']=1;
        item['max']=15;
        this.currentKeyVal['key'+item.key]=1; 
      } 
    });
    //RF天线性能配置
    this.rfFunctionList.forEach(item=>{
        if(item.key=='0b'){
            this.currentKeyVal['key'+item.key]=this.bandWidthOption[0].value;  
        }else if(item.key=='0e'){
        item['min']=5;
        item['max']=19;
        this.displayHitCount=5;
        this.currentKeyVal['key'+item.key]=this.hitCountList.find(data=>{
            return data.name=='5';
        }).value;
      } else if(item.key=='1b' || item.key=='1c'){
        item['min']=1;
        item['max']=30;
        this.currentKeyVal['key'+item.key]=1;  
      } else if(item.key=='12'){
        item['min']=1;
        item['max']=15;
        this.currentKeyVal['key'+item.key]=1; 
      } 
    });
    //报警设置
    this.rfAlarmList.forEach(item=>{
      if(item.key=='03'){
        this.currentKeyVal['key'+item.key]=this.alermColorList[0].value; 
      } else if(item.key=='19'){
        this.currentKeyVal['key'+item.key]=this.lightColorList[0].value; 
      } else if(item.key=='01'){
        this.currentKeyVal['key'+item.key]=this.toneList[0].value; 
      } else if(item.key=='02'){
        this.currentKeyVal['key'+item.key]=this.soundLengthLish[0].value; 
      } else if(item.key=='0c'){
        this.currentKeyVal['key'+item.key]=this.alermEnableList[0].value; 
      }
    }); 
    //硬件版本
    this.currentKeyVal['key00']="1.0.0";
    Mysocket.oncloseWS();
    setTimeout(()=>{
        Mysocket.createSocket();
        this.initSocketMsg();
        this.chgAntType();
    },500);
  } 
  exit(){
    this.close.emit(true);
  }
    ngOnDestroy(): void {
        Mysocket.oncloseWS();
    }
    //主副天线切换
    chgAntType(){
        let  data={LoginForm:this.LoginForm};
        this.homeService.chgAntType(data).subscribe(res=>{
            if(res.status=1){
                this.message.success(this.translateService.instant('successfully'));
            }else {
                this.message.error(res.message);
            }
        });
    }
    initSocketMsg(){
        //接收信息
        let _this=this;
        window.addEventListener("onmessageWS",function(e){
            let Msg=(JSON.parse(e['detail']['data']['data']));
            console.log(Msg);
            switch(Msg.moduleCode){
                //天线性能
                case '0e':
                    _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    _this.displayHitCount=_this.hitCountList.find(item=>{
                        return item.value==Msg.val;
                    }).name;
                    break;
                case '1b':
                case '1c':
                case '12':
                case '0b':
                //报警设置
                case '01':
                case '02':
                case '03':
                case '19':
                case '0c':
                //波形调试
                case '0f':
                case '10':
                case '13':
                case '14':
                    _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    break;
                case 'f201':
                    if(_this.state){
                        _this.dealWaveChart(201,JSON.parse(Msg.val));
                    }
                    break;
                case 'f202':
                    if(_this.state){
                        _this.dealWaveChart(202,JSON.parse(Msg.val));
                    }
                    break;
                case '00':
                    //如果硬件版本号已经有值，不再改变，固定;当音调变化时，硬件版本号会解析为0.0（不准确）
                    if(Msg.val!='0.0'){
                        _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
                    }
                    break;
                case '0f0f':
                    _this.isW1LightShow=true;
                    setTimeout(()=>{
                        _this.isW1LightShow=false;
                    },10000);
                    break;
                case '1010':
                    _this.isW2LightShow=true;
                    setTimeout(()=>{
                        _this.isW2LightShow=false;
                    },10000);
                    break;
                case '0d0d':
                    _this.isBothLightShow=true;
                    setTimeout(()=>{
                        _this.isBothLightShow=false;
                    },10000);
                    break;
                case 'close':
                    Mysocket.oncloseWS();
                    _this.offLine.emit(true);
                    break;
                default:
                    break;
            }
        });
    }
    dealWaveChart(num,val){
        if(num==201){
            this.waveDataY1List=Object.values(val);
        } else if(num==202){
            this.waveDataY2List=Object.values(val);
        }
        this.showWave();
    }
  //展示波形图
  showWave(){
    this.signalWaveOption={ 
      grid:{
        x:"40px",   //左侧与y轴的距离
        y: "30px",   //top部与x轴的距离
        x2:"20px",   //右侧与y轴的距离
        y2: "50px"    //bottom部与x轴的距离
      },     
      legend: {
          data:['W1','W2'],
          x: 'center',
          y:'top',
          icon:'roundRect'
      },
      tooltip : {
          trigger: 'axis',
          triggerOn:"mousemove", 
          axisPointer: {
              type: 'cross',
              animation: true,
              label: {
                  backgroundColor: '#505765'
              }
          },
      },
      xAxis : [
          {
              type : 'category',//类目   
              data : this.waveDataXList,
              boundaryGap: true,
          }
      ],
      yAxis: [
          {
              type: 'value',
              minInterval : 1,   
              name:this.translateService.instant('eas_rfwave_fz')
          },
      ],
      series:this.signalWave==this.rfWaveOption2[0].value?
        {
          symbol: "none",
          name:'W1',
          type:'line',
          color: '#074eb1', 
          data:this.waveDataY1List,
        }: 
        (this.signalWave==this.rfWaveOption2[1].value?
        {
          symbol: "none",
          name:'W2',
          type:'line',
          color:'#EF3117', 
          data:this.waveDataY2List,
      }  :[
        {
          symbol: "none",
          name:'W1',
          type:'line',
          color: '#074eb1', 
          data:this.waveDataY1List,
        },
        {
          symbol: "none",
          name:'W2',
          type:'line',
          color:'#EF3117', 
          data:this.waveDataY2List,
        } 
      ])
    };
  }
    //报警测试
    testAlarm(){
        let moduleCode=this.alarmTestItem['key'];
        this.sendAntConfigOrder(moduleCode,0);
    }
    //命令下发
   sendAntConfigOrder(code,e){
        let data={
            LoginForm:storage.getSessionStorage('LoginForm'),
            DeviceMessage:{
                moduleCode:code,
                val:e,
                moduleType:1
            }
        };
        this.homeService.order(data).subscribe(res=>{
            if(res.status==1){
                this.message.success(this.translateService.instant('eas_order_success'));
            }else {
                this.message.error(res.message);
            }
        });
    }
  //状态改变
  stateChange(){
    let val;
    if(this.state){
      //运行
      this.signalWave=this.rfWaveOption2[0].value;
      val=this.rfWaveOption2[0].value;
    } else {
      //停止
      this.signalWave='';
      val=this.rfWaveOption1[0].value;
      this.waveDataY1List=[];
      this.waveDataY2List=[];
    }
    this.showWave();
    this.chgWaveform(val);
  }
  //状态改变2
  stateChange2(value){
    if(!this.state){
      this.state=true;
    }
    this.signalWave=value;
    this.chgWaveform(this.signalWave);
    this.showWave();
  }
   //波形图启/停
   chgWaveform(val){
    let data={
        LoginForm:this.LoginForm,
        DeviceMessage:{val}
    }
    this.homeService.chgWaveform(data).subscribe(res=>{
        if(res.status=1){
            this.message.success(this.translateService.instant('successfully'));
        }else {

        }
    });
}
//    //选择天线时
//    chooseSameAnt(item){
//     this.sameAnt=item.id;
//   }
    //读取参数
    readParam(){
        this.sendAntConfigOrder(this.readParamItem['key'],0);
    }
  //恢复出厂设置
  restoreFactory(){
    this.modalService.confirm({
      nzTitle     : this.translateService.instant('tip'),
      nzContent   : `<b>`+this.translateService.instant('eas_note_restore')+`</b>`,
      nzOkText    : this.translateService.instant('OK'),
      nzOkType    : 'primary',
      nzOnOk      : () => {
        //如果波形图运行，先停止
        if(this.state){
          this.state=false;
          this.stateChange();
        }
        this.sendAntConfigOrder(this.restoreFactoryItem['key'],0);
      },
      nzCancelText: this.translateService.instant('cancel'),
      nzOnCancel  : () => {
      }
    });
    
  }
}
